<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { useUserStore } from '@vben/stores';

import { message, Skeleton } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenForm } from '#/adapter/form';
import { getAdminUserInfo, putAdminUserInfo } from '#/api/admin/userInfo';

const loading = ref<boolean>(true);

async function onSubmit(values: Record<string, any>) {
  const { msg } = await putAdminUserInfo(values);
  message.success(msg);
  const userStore = useUserStore();
  userStore.setUserInfo({
    user_nickname: values.user_nickname,
    avatar: values.avatar,
    signature: values.signature,
  });
}

const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'user_nickname',
      label: '昵称',
      rules: 'required',
    },

    {
      component: 'Select',
      componentProps: {
        options: [
          { label: '男', value: 1 },
          { label: '女', value: 2 },
          { label: '保密', value: 0 },
        ],
        placeholder: '请选择',
      },
      fieldName: 'sex',
      label: '性别',
      rules: 'required',
    },
    {
      component: 'DatePicker',
      fieldName: 'birthday',
      label: '生日',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'user_url',
      label: '个人网址',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'signature',
      label: '个性签名',
    },
  ],
});

const onGetUserInfo = async () => {
  const { data } = await getAdminUserInfo();
  if (data.user) {
    data.user.birthday =
      data.user.birthday === 0
        ? dayjs(dayjs(new Date()).format('YYYY-MM-DD'))
        : dayjs(dayjs(data.user.birthday * 1000).format('YYYY-MM-DD'));
    const formData = data.user;
    formApi.setValues(formData);
  }
  loading.value = false;
};

onMounted(async () => {
  await onGetUserInfo();
});
</script>

<template>
  <Skeleton :loading="loading">
    <Form />
  </Skeleton>
</template>
